import { getArea, getLength } from "ol/sphere";
import Overlay from "ol/Overlay";

export const showTip = (evt: any, type: any, baseMap: any) => {
  // 绘制的图形的几何信息
  let sketch = evt.feature;
  let geom = sketch.getGeometry();
  console.log("geom", geom);
  let result;

  let measureTooltipElement = null;
  let measureTooltip = null;
  let tooltipCoord;

  switch (type) {
    case "Point":
      break;
    case "LineString":
      result = formatLength(geom);
      tooltipCoord = geom.getLastCoordinate();
      break;
    case "Polygon":
      result = formatArea(geom);
      tooltipCoord = geom.getLastCoordinate();
      break;
    case "Circle":
      result = formatCircleArea(geom, baseMap);
      tooltipCoord = geom.getLastCoordinate();
      break;
    case "Rectangle":
      result = formatArea(geom);
      tooltipCoord = geom.getLastCoordinate();
      break;
  }
  let tip = createMeasureTooltip(measureTooltipElement, measureTooltip, result);
  tip.setPosition(tooltipCoord);
  return tip;
};

const formatLength = function (line: any) {
  // 距离
  const length = getLength(line, { projection: "EPSG:4326" });
  let output;
  if (length > 100) {
    output = Math.round((length / 1000) * 100) / 100 + " " + "km";
  } else {
    output = Math.round(length * 100) / 100 + " " + "m";
  }
  return output;
};

const formatArea = function (polygon: any) {
  // 面积
  const area = getArea(polygon, { projection: "EPSG:4326" });
  console.log("area;", area);
  let output;
  if (area > 10000) {
    output = Math.round((area / 1000000) * 100) / 100 + " " + "km²";
  } else {
    output = Math.round(area * 100) / 100 + " " + "m²";
  }
  return output;
};

const formatCircleArea = function (circle: any, baseMap: any) {
  //半径
  let metersPerUnit = baseMap.getView().getProjection().getMetersPerUnit();
  console.log("metersPerUnit;", metersPerUnit);
  const radius = circle.getRadius() * metersPerUnit;
  const area = Math.PI * radius * radius;
  console.log("area", area);
  let output;
  if (area > 10000) {
    output = Math.round((area / 1000000) * 100) / 100 + " " + "km²";
  } else {
    output = Math.round(area * 100) / 100 + " " + "m²";
  }
  return output;
};

// tip样式
const createMeasureTooltip = (i: any, tip: any, result: any) => {
  if (i) {
    i.parentNode.removeChild(i);
  }
  i = document.createElement("div");
  // css
  i.style.cssText = style;
  i.innerHTML = result;
  tip = new Overlay({
    element: i,
    offset: [0, -15],
    positioning: "bottom-center",
    stopEvent: false,
    insertFirst: false,
  });
  return tip;
};

let style = "position: relative; background: rgba(195, 59, 83, 1);" + "border-radius: 4px; color: white; padding: 4px 8px;" + "opacity: 1; white-space: nowrap; font-size: 12px;" + "cursor: default; user-select: none;";
